/**
 * An Ajax Arrow
 */
Arrows.Ajax = function(defaults) {
	if (!(this instanceof Arrows.Ajax)) {
		var a = new Arrows.Ajax();
		Arrows.Ajax.apply(a, arguments);
		return a;
	}
	// Call the parent class' constructor
	Arrows.Component.apply(this, arguments);

	this._defaults = defaults;

	return this;
};
Arrows.Ajax.prototype = new Arrows.Component;
/**
 * Make the ajax call.
 *
 * @param relay {Arrows.Relay} The relay
 * @param args {Array} The arguments
 */
Arrows.Ajax.prototype.begin = function(relay, args) {
	var self = this;

	args = $.extend({}, this._defaults, (args || [])[0]);

	var oldSuccess = args.success;
	args.success = function(result) {
		if (oldSuccess) oldSuccess(result);

		relay.fire(self, "complete", [result]);
	};

	relay.addComponent(this, {
		"cancel": function(component) {
			if (self !== component) {
				c.abort();
			}
		}
	});
	

	var c = $.ajax(args);
};
/**
 * An Event Arrow
 */
Arrows.Event = function(eventName) {
	if (!(this instanceof Arrows.Event)) {
		var a = new Arrows.Event();
		Arrows.Event.apply(a, arguments);
		return a;
	}
	Arrows.Component.apply(this, arguments);

	this._eventName = eventName;

	return this;
};
Arrows.Event.prototype = new Arrows.Component;
/**
 * Hook the event on the element.
 *
 * @param relay {Arrows.Relay} The relay
 * @param args {Array} The arguments
 */
Arrows.Event.prototype.begin = function(relay, args) {
	var self = this;

	var target = $(args[0]);

	function cancel() {
		target.unbind(self._eventName, handler);
	}

	function handler(evt) {
		cancel();

		relay.fire(self, "progress", []);
		relay.fire(self, "complete", [evt, target]);
	}

	relay.addComponent(this, {
		"cancel": function(component) {
			if (component !== self) {
				cancel();
			}
		}
	});

	target.bind(self._eventName, handler);
};

jQuery.Arrows = Arrows;
